﻿using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;

namespace WPF40_FileUploadCustonControl
{
    /// <summary>
    /// Follow steps 1a or 1b and then 2 to use this custom control in a XAML file.
    ///
    /// Step 1a) Using this custom control in a XAML file that exists in the current project.
    /// Add this XmlNamespace attribute to the root element of the markup file where it is 
    /// to be used:
    ///
    ///     xmlns:MyNamespace="clr-namespace:WPF40_FileUploadCustonControl"
    ///
    ///
    /// Step 1b) Using this custom control in a XAML file that exists in a different project.
    /// Add this XmlNamespace attribute to the root element of the markup file where it is 
    /// to be used:
    ///
    ///     xmlns:MyNamespace="clr-namespace:WPF40_FileUploadCustonControl;assembly=WPF40_FileUploadCustonControl"
    ///
    /// You will also need to add a project reference from the project where the XAML file lives
    /// to this project and Rebuild to avoid compilation errors:
    ///
    ///     Right click on the target project in the Solution Explorer and
    ///     "Add Reference"->"Projects"->[Select this project]
    ///
    ///
    /// Step 2)
    /// Go ahead and use your control in the XAML file.
    ///
    ///     <MyNamespace:CustomControl1/>
    ///
    /// </summary>
     

    // Created for www.dotnetcurry.com by Mahesh Sabnis

    // Modified by Fernando cerqueira
    // Improvement layout, behavior and new propreties

    public class FileUploadCustomControl : Control
    {

        TextBox _txtFileName = new TextBox();
        Button _btnBrowse = new Button();
        private bool _noraisechange;
        static FileUploadCustomControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(FileUploadCustomControl), new FrameworkPropertyMetadata(typeof(FileUploadCustomControl)));
        }

        public string FileName
        {
            get { return (string)GetValue(FileNameProperty); }
            set
            {
                SetValue(FileNameProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for FileName.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FileNameProperty =
            DependencyProperty.Register("FileName", typeof(string), typeof(FileUploadCustomControl),
                new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, PropertyChangedCallback));

        private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            ((FileUploadCustomControl) dependencyObject)._txtFileName.Text = (string)dependencyPropertyChangedEventArgs.NewValue;
        }


        public string FileFilter
        {
            get { return (string)GetValue(FileFilterProperty); }
            set { SetValue(FileFilterProperty, value); }
        }

        public static readonly DependencyProperty FileFilterProperty =
            DependencyProperty.Register("FileFilter", typeof(string), typeof(FileUploadCustomControl),
                new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));


        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _txtFileName = Template.FindName("TXT_FILE_NAME", this) as TextBox;

            _btnBrowse = Template.FindName("BTN_BROWSE_FILE", this) as Button;
            if (_btnBrowse != null) _btnBrowse.Click += BtnBrowseClick;
            if (_txtFileName != null) _txtFileName.LostFocus += TxtFileNameLostFocus;
            if (_txtFileName != null) _txtFileName.TextChanged += TxtFileNameTextChanged;
        }

        private void TxtFileNameTextChanged(object sender, TextChangedEventArgs e)
        {
            _noraisechange = false;
        }

        private void TxtFileNameLostFocus(object sender, RoutedEventArgs e)
        {
            if (!_noraisechange && !string.IsNullOrEmpty(_txtFileName.Text))
            {
                e.Handled = true;
                RaiseEvent(new RoutedEventArgs(FileNameChangedEvent));
            }
        }

        void BtnBrowseClick(object sender, RoutedEventArgs e)
        {
            var fileDIalog = new OpenFileDialog();
            var filter = FileFilter;
            if (string.IsNullOrEmpty(filter))
            {
                filter = "All files (*.*)|*.*";
            }
            fileDIalog.Filter = filter;
            fileDIalog.AddExtension = true;
            if (fileDIalog.ShowDialog() == true)
            {
                FileName = fileDIalog.FileName;
                _txtFileName.Text = FileName; 
            }
            RaiseEvent(new RoutedEventArgs(FileNameChangedEvent));
            _noraisechange = true;
        }


        public event RoutedEventHandler FileNameChanged
        {
            add { AddHandler(FileNameChangedEvent, value); }
            remove { RemoveHandler(FileNameChangedEvent, value); }
        }

        public static readonly RoutedEvent FileNameChangedEvent =
            EventManager.RegisterRoutedEvent("FileNameChanged",
            RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(FileUploadCustomControl));

    }
}
